package com.aios.action.home;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.aios.action.settings.switches.SwitchesListAction;
import com.aios.entity.Controller;
import com.aios.service.ControllerService;
import com.opensymphony.xwork2.ActionSupport;

public class HomeAction extends SwitchesListAction {

	private static Logger logger = Logger.getLogger(HomeAction.class);
	
	private static final long serialVersionUID = 1L;
	@Autowired private ControllerService controllerService;
	private List<Controller> controllerList;
	
	private static final String[]  MOBILE_AGENTS = {
		  "iphone", "ipad", "NEC", "samsung", "HTC", "sony",
		  "midp", "j2me", "avant", "docomo",
		        "240x320", "opwv", "chtml",
		        "pda", "windows ce", "mmp/",
		        "blackberry", "mib/", "symbian",
		        "wireless", "nokia", "hand", "mobi",
		        "phone", "cdm", "up.b", "audio",
		        "SIE-", "SEC-", "mot-", "mitsu", "sagem",
		        "alcatel", "lg", "eric", "vx",
		        "philips", "mmm", "xx",
		        "panasonic", "sharp", "wap", "sch",
		        "rover", "pocket", "benq", "java",
		        "pt", "pg", "vox", "amoi",
		        "bird", "compal", "kg", "voda",
		        "sany", "kdd", "dbt", "sendo",
		        "sgh", "gradi", "jb", "dddi",
		        "novarra", "palmos", "palmsource", "moto"
		    };
	
		 public  boolean isMobileAccess() {
		  HttpServletRequest request = ServletActionContext.getRequest();
		  String userAgent = request.getHeader("USER-AGENT");
		  if(userAgent != null) {
		   userAgent = userAgent.toLowerCase();
		   for(String string : MOBILE_AGENTS) {
		    if(userAgent.indexOf(string) >= 0) {
		     return true;
		    }
		   }
		  }
		  
		  return false;
		 }
	
	public String view() {
		
		String response =  super.execute();
		
		if(!response.equals(ActionSupport.SUCCESS))
			return response;
		
		else {
			
			try {
				listPopulateHelper();
				return SUCCESS;
				
			} catch(Exception e) {
				logger.error(e.toString());
				return INPUT;
			}
		}
	}
	
	private void listPopulateHelper() {
		populateCameraControllerList();
	}
	
	private void populateCameraControllerList() {
		try {
			controllerList = controllerService.findControllerByUserID(getSessionUserVariable().getId());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public List<Controller> getControllerList() {
		return controllerList;
	}

	public void setControllerList(List<Controller> controllerList) {
		this.controllerList = controllerList;
	}
	
}
